package com.jc.service.yxreturnorder;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.UUIDUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.*;
import com.jc.framework.enums.LogType;
import com.jc.framework.enums.OrderStatus;
import com.jc.framework.enums.YanXuanServiceName;
import com.jc.service.api.yx163.YanXuanAdapter;
import com.jc.service.api.yx163.order.YanXuanOrderService;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.publicImg.PublicImgService;
import com.jc.service.xorderReturnSku.XorderReturnSkuService;
import com.jc.service.xorderreturn.XorderReturnService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class YXReturnOrderServiceImpl extends YanXuanAdapter implements YXReturnOrderService {

    @Autowired
    private XorderService xorderService;
    @Autowired
    private OrderProductsService orderProductsService;
    @Autowired
    private PublicImgService publicImgService;
    @Autowired
    private XorderReturnSkuService xorderReturnSkuService;
    @Autowired
    private XorderReturnService xorderReturnService;
    @Autowired
    private YanXuanOrderService yanXuanOrderService;



    @Transactional
    @Override
    public Map<String,Object> updateReturnPro(Map<String, Object> param) {
       Map<String,Object> resultMap = new HashMap<>();
        LinkedHashMap<String,Object> paramYX = new LinkedHashMap<>();
        Map<String,Object> applySku = new HashMap<>();

        String channelOrderId = param.get("channelOrderId").toString();
        String reason = param.get("reason").toString();

        //生成申请单, 和申请单SKU关联表 图片
        //订单全部退货 查询所有sku
        List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
            setChannelOrderId(channelOrderId);
        }});
        if (CollectionUtils.isEmpty(xorders) || xorders.size() > 1){
            throw new BaseServiceException("订单信息错误![订单存在多个或者订单不存在]");
        }
        Xorder xorder = xorders.get(0);
        //保存申请单
        List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
            setOrderId(xorder.getId());
        }});

        XorderReturn xorderReturn = new XorderReturn();

        if (CollectionUtils.isNotEmpty(xorderReturns)){
            xorderReturn = xorderReturns.get(0);
        }else{
            xorderReturn.setApplicantName(xorder.getConsigneeName());//发起人姓名
            xorderReturn.setApplicantPhone(xorder.getConsigneeMobile());//手机号
            xorderReturn.setRequestId(UUIDUtil.getUUID());//售后Id
            xorderReturn.setOrderId(xorder.getId());
            xorderReturn.setChannelOrderId(channelOrderId);
            xorderReturn.setReasonDesc(param.get("reasonDesc").toString());//退货详细信息
            xorderReturn.setCreateTime(new Date());
            String isPay = null;
            if ("质量问题".equals(reason) && param.get("imgUrlList") == null){
                isPay = "2";
            }else{
                isPay = "1";
            }
            xorderReturn.setIsPay(isPay);
            xorderReturnService.add(xorderReturn,false);
        }
        XorderReturn finalXorderReturn = xorderReturn;
        //保存申请单关联表
        //查询订单关联表 . 多个sku退货
        List<OrderProducts> orderProducts = orderProductsService.queryAllByIn(param.get("orderProids").toString());
        for (OrderProducts orderProduct:orderProducts){
            //保存至sku退货单关联表
            XorderReturnSku xorderReturnSku = new XorderReturnSku();
            //查询是否存在 如果存在 不保存
            List<XorderReturnSku> xorderReturnSkus = xorderReturnSkuService.queryAll(new XorderReturnSku() {{
                setXorderReturnId(finalXorderReturn.getId());
            }});
            if (CollectionUtils.isNotEmpty(xorderReturnSkus)){
                xorderReturnSku = xorderReturnSkus.get(0);
            }else{
                xorderReturnSku.setSkuId(orderProduct.getId());
                xorderReturnSku.setXorderReturnId(xorderReturn.getId());
                xorderReturnSku.setSkuNum(Long.valueOf(orderProduct.getProductNums()));
                xorderReturnSku.setSkuOriginalPrice(orderProduct.getSalePrice());
                xorderReturnSku.setSubtotalPrice(orderProduct.getSalePrice().multiply(new BigDecimal(orderProduct.getProductNums())));
                xorderReturnSku.setCreateTime(new Date());
                xorderReturnSkuService.add(xorderReturnSku,false);
            }
            // 上传图片
            if ("质量问题".equals(reason) && param.get("imgUrlList") == null){
                throw new BaseServiceException("退货原因为【质量问题】时,必须上传图片!");
            }
            //图片
            List<Map<String,Object>> imgList = new ArrayList<>();
            String[] imgUrlLists = param.get("imgUrlList").toString().split(";");
            Long x = 0L;
            XorderReturnSku finalXorderReturnSku = xorderReturnSku;
            for (String imgUrl : imgUrlLists){
                x++;
                //保存图片
                Long finalX = x;
                publicImgService.add(new PublicImg(){{
                    setType("0");
                    setBusinessId(finalXorderReturnSku.getId());
                    setCreateTime(new Date());
                    setSort(finalX);
                    setUrl(imgUrl);
                }},false);
                imgList.add(new HashMap<String, Object>(){{
                    put("url",imgUrl);
                    String[] split = imgUrl.split("/");
                    String fileName = split[split.length-1];
                    put("fileName",fileName);
                }});
            }
            applySku.put("packageId",orderProduct.getSupplierReturnId());//包裹id
            applySku.put("skuId",orderProduct.getSupplierProductId());//skuId
            applySku.put("count",orderProduct.getProductNums());
            applySku.put("applySkuReason",new HashMap<String,Object>(){{
                    put("reason",param.get("reason"));//退换货原因——指定文案：无理由、质量问题
                    put("reasonDesc",param.get("reasonDesc"));
                }});
            applySku.put("applyPicList",imgList);
            applySku.put("originalPrice",orderProduct.getSalePrice());
            applySku.put("subtotalPrice",orderProduct.getSalePrice().multiply(new BigDecimal(orderProduct.getProductNums())));
        }
        //判断订单状态 未发货直接取消  已发货 走下边流程
        if(!xorder.getOrderStatus().equals(OrderStatus.ALREADY_CONFIRM_RECEIPT.getName()) && !xorder.getOrderStatus().equals(OrderStatus.outstorage.getName())){
            //取消订单 , 商品为发货 /
            YanXuanResult yanXuanResult = yanXuanOrderService.canelOrderByYanXuan(String.valueOf(xorder.getId()));
            System.out.println("========================取消订单 网易返回 code"+ yanXuanResult.getCode() +" ; 返回表述 : " + yanXuanResult.getMessage() +" ; 返回数据 : "+yanXuanResult.getResult());;
            if ("200".equals(yanXuanResult.getCode())){
                //修改订单状态
//                Map<String,String> map = (Map)yanXuanResult.getResult();
                List<Map<String,String>> list = JSONObject.parseObject(String.valueOf(yanXuanResult.getResult()), List.class);
                Map<String, String> map = list.get(0);
                if (String.valueOf(map.get("cancelStatus")).equals("0")){
                    //不允许退货
                    xorder.setOrderStatus(OrderStatus.NO_RETURN_ALLOWED.getName());
                    xorderReturn.setStatus("11");
                    xorderReturn.setDenyReason(map.get("rejectReason"));
                    resultMap.put("code",5001);
                    resultMap.put("msg","取消订单失败, 请先确认收货!");
                    return resultMap;
                }else if (String.valueOf(map.get("cancelStatus")).equals("1")){
                    //允许取消
                    xorder.setOrderStatus(OrderStatus.NO_RETURN_ALLOWED.getName());
                    xorderReturn.setStatus("8");
                    xorderReturn.setDenyReason(map.get("rejectReason"));
                    resultMap.put("code",10000);
                    resultMap.put("data","SUCCESS");
                    return resultMap;
                }else if (String.valueOf(map.get("cancelStatus")).equals("2")){
                    //待审核
                    xorder.setOrderStatus(OrderStatus.NO_RETURN_ALLOWED.getName());
                    xorderReturn.setStatus("9");
                    xorderReturn.setDenyReason(map.get("rejectReason"));
                    resultMap.put("code",10000);
                    resultMap.put("data","SUCCESS");
                    return resultMap;
                }
                //修改订单状态
                xorderService.modify(xorder,false);
                //修改申请单状态
                xorderReturnService.modify(xorderReturn,false);
                resultMap.put("code",10000);
                resultMap.put("data","SUCCESS");
                return resultMap;
            }else{
                //取消订单失败 .
                System.out.println("取消订单失败, 请先确认收货!");
                resultMap.put("code",5001);
                resultMap.put("data","取消订单失败, 请先确认收货!");
                return resultMap;
            }
        }
        LinkedHashMap<String, Object> _paramYX = new LinkedHashMap<>();
        _paramYX.put("requestId", UUIDUtil.getUUID());//售后申请Id
        _paramYX.put("orderId",channelOrderId);//订单号
        _paramYX.put("applyUser",new HashMap<String,Object>(){{
            put("name",xorder.getConsigneeName());
            put("mobile",xorder.getConsigneeMobile());
        }});//售后申请人
        _paramYX.put("applySku",applySku);//sku信息
        paramYX.put("applyInfo",JSONObject.toJSONString(_paramYX));
        paramYX.put("method", YanXuanServiceName.YANXUAN_ORDER_REFUND_APPLY.getName());
        paramYX.put("logType", LogType.YANXUAN_RETURN);
        LinkedHashMap<String, Object> _params = this.getSign(paramYX);
        YanXuanResult yanXuanResult = this.postYanXuan(_params);
        System.out.println("========================取消订单 网易返回 code : "+ yanXuanResult.getCode() +" ; 返回表述 : " + yanXuanResult.getMessage() +" ; 返回数据 : "+yanXuanResult.getResult());;
        //异常
        if (!"200".equals(yanXuanResult.getCode())){
            throw new BaseServiceException(yanXuanResult.getMessage());
        }
        System.out.println("==================取消订单返回值: "+ yanXuanResult.getResult());
        List<Map<String,Object>> yanxuanRetunList = JSONObject.parseObject(String.valueOf(yanXuanResult.getResult()) , List.class);
        Map<String, Object> yanxuanRetun = yanxuanRetunList.get(0);
        //提交成功 修改信息;
        XorderReturn finalXorderReturn1 = xorderReturn;
        xorderReturnService.modify(new XorderReturn(){{
            setId(finalXorderReturn1.getId());
            //申请单Id
            setReturnFromId(yanxuanRetun.get("applyId").toString());
            if(yanxuanRetun.get("status") != null){
                setStatus(yanxuanRetun.get("status").toString());
            }
            if(yanxuanRetun.get("denyReason") != null){
                setDenyReason(yanxuanRetun.get("denyReason").toString());
            }
            if (yanxuanRetun.get("returnType") != null){
                setIsPay(yanxuanRetun.get("returnType").toString());
            }
        }},false);
        //修改订单状态
        xorder.setOrderStatus(OrderStatus.wait_auditing.getName());
        xorderService.modify(xorder,false);
        resultMap.put("code",10000);
        resultMap.put("data","SUCCESS");
        return resultMap;
    }

    @Override
    public Boolean bindingLogisticsNumber(Map<String, Object> param) {
        //查询售后单 .
        //查询订单
        List<Xorder> xorderList = xorderService.queryAll(new Xorder() {{
            setChannelOrderId(param.get("channelOrderId").toString());
        }});
        if (CollectionUtils.isEmpty(xorderList)){
            throw new BaseServiceException("当前订单存在! channelOrderId  = "+ param.get("channelOrderId").toString());
        }
        Xorder xorder = xorderList.get(0);
        List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
            setOrderId(xorder.getId());
        }});
        if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() > 1){
            throw new BaseServiceException("申请单存在多条或不存在 orderId = " + xorder.getId());
        }
        XorderReturn xorderReturn = xorderReturns.get(0);
        String returnFromId = xorderReturn.getReturnFromId();
        if (StringUtils.isEmpty(returnFromId)){
            throw new BaseServiceException("申请单正在审核中，请耐心等待！");
        }
        List<org.json.JSONObject> logisticsInformation = new ArrayList<>();
        String expressInfo = param.get("expressInfo").toString();
        List<Map<String,Object>> list = JSONObject.parseObject(expressInfo, List.class);
        for (Map<String,Object> exp :list){
            logisticsInformation.add(new org.json.JSONObject(){{
                put("trackingCompany",exp.get("trackingCompany"));
                put("trackingNum",exp.get("trackingNum"));
            }});
        }
        //拼装信息发送给网易
        LinkedHashMap<String,Object> YXparam = new LinkedHashMap<>();
        YXparam.put("applyId",returnFromId);
        YXparam.put("expressInfo",logisticsInformation);
        YXparam.put("method",YanXuanServiceName.YANXUAN_LOGISTICS_INFORMATION.getName());
        YXparam.put("logType", LogType.YANXUAN_LOGISTICS_INFORMATION);
        LinkedHashMap<String, Object> sign = getSign(YXparam);
        System.out.println("退货 : 绑定物流单号   请求参数 "+ sign);
        YanXuanResult yanXuanResult = postYanXuan(sign);
        System.out.println("退货 : 绑定物流单号   返回数据 code : " + yanXuanResult.getCode() + " 返回数据 : " + yanXuanResult.getResult()+" 返回错误描述 : "+ yanXuanResult.getMessage());
        if (yanXuanResult.getCode().equals("200")){
//            修改订单状态  带网易确认收货
            xorderService.modify(new Xorder(){{
                setId(Long.valueOf(param.get("orderId").toString()));
                setOrderStatus(OrderStatus.CONFIRM_RECEIPT.getName());
            }},false);
            return true;
        }else{
            throw new BaseServiceException(yanXuanResult.getMessage());
        }
    }

    @Override
    public Boolean confirmReceipt(Map<String, Object> param) {
        String channelOrderIds = param.get("channelOrderIds").toString();
        String channelSource = param.get("channelSource").toString();
        String[] ids = channelOrderIds.split(",");
        for (String id : ids){
            List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
                setChannelOrderId(id);
                setChannelSource(channelSource);
            }});
            if (CollectionUtils.isEmpty(xorders) || xorders.size()>1){
                throw new BaseServiceException("订单信息错误! channelOrderId = "+id);
            }
            Xorder xorder = xorders.get(0);
            if (!xorder.getOrderStatus().equals(OrderStatus.outstorage.getName())){
                throw new BaseServiceException("当前订单状态异常，无法确认收货！");
            }
            List<OrderProducts> orderProductList = orderProductsService.queryAll(new OrderProducts() {{
                setOrderId(xorder.getId());
            }});
            if (CollectionUtils.isEmpty(orderProductList) || orderProductList.size()>1){
                throw new BaseServiceException("订单信息错误! xorderId = "+xorder.getId());
            }
            OrderProducts orderProducts = orderProductList.get(0);
            //获取包裹Id
            LinkedHashMap<String,Object> YXparam = new LinkedHashMap<>();
            YXparam.put("orderId",xorder.getChannelOrderId());
            YXparam.put("packageId",orderProducts.getSupplierReturnId());
            YXparam.put("confirmTime",DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT));
            YXparam.put("method",YanXuanServiceName.YANXUAN_RECEIVED_CONFIRM.getName());
            YXparam.put("logType",LogType.YANXUAN_CONFIRM_RECEIPT);
            LinkedHashMap<String, Object> _YXparam = getSign(YXparam);
            YanXuanResult yanXuanResult = postYanXuan(_YXparam);
            System.out.println("=============请求网易,确认收货,请求参数 : "+_YXparam+"==========返回code : " + yanXuanResult.getCode() + "  ===返回描述 : "+ yanXuanResult.getMessage() +"  ====返回数据: "+yanXuanResult.getResult());
            if (!String.valueOf(yanXuanResult.getCode()).equals("200")){
                throw new BaseServiceException(yanXuanResult.getMessage());
            }
            xorder.setOrderStatus(OrderStatus.ALREADY_CONFIRM_RECEIPT.getName());
            xorderService.modify(xorder,false);

            //查看是否存在申请单,如果存在发起售后申请
            List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
                setOrderId(xorder.getId());
            }});
            if (CollectionUtils.isEmpty(xorderReturns)){
                return true;
            }
            //发起售后
            XorderReturn xorderReturn = xorderReturns.get(0);
            List<XorderReturnSku> xorderReturnSkus = xorderReturnSkuService.queryAll(new XorderReturnSku() {{
                setXorderReturnId(xorderReturn.getId());
            }});
            if(CollectionUtils.isEmpty(xorderReturnSkus)){
                System.out.println("=================申请单不存在 xorderReturnId"+xorderReturn.getId());
                return true;
            }
            XorderReturnSku xorderReturnSku = xorderReturnSkus.get(0);
            updateReturnPro(new HashMap<String, Object>(){{
                put("channelOrderId",id);
                String reasonDesc;
                if ("1".equals(xorderReturn.getIsPay())){
                    reasonDesc = "无理由";
                }else{
                    reasonDesc = "质量问题";
                }
                put("reason",reasonDesc);
                put("reasonDesc",xorderReturn.getReasonDesc());
                //查询图片
                List<PublicImg> publicImgs = publicImgService.queryAll(new PublicImg() {{
                    setType("0");
                    setBusinessId(xorderReturnSku.getId());
                }});
                List<String> imgUrlList = new ArrayList<>();
                for (PublicImg publicImg:publicImgs) {
                    imgUrlList.add(publicImg.getUrl());
                }
                put("imgUrlList",StringUtils.join(imgUrlList,";"));
            }});
        }
        return true;
    }

    /**
     * 取消售后
     * */
    @Override
    public Map<String, Object> cancelAftersale(String applyId) {
       Map<String,Object> resultMap = new HashMap<>();
       resultMap.put("code",10000);
       LinkedHashMap<String,Object> param = new LinkedHashMap<>();
       param.put("applyId",applyId);
       param.put("method",YanXuanServiceName.YANXUAN_REFUND_CANCEL.getName());
       param.put("logType",LogType.CANCEL_AFTER_SALE);
       LinkedHashMap<String, Object> sign = getSign(param);
       YanXuanResult yanXuanResult = postYanXuan(sign);
       if ("200".equals(yanXuanResult.getCode())){
           resultMap.put("data","SUCCESS");
       }else{
           resultMap.put("code",9999);
           resultMap.put("msg","取消售后错误");
       }
       return  resultMap;
    }

}
